package demoflink.demo;

import demoflink.entity.WaterSensor;
import demoflink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * 侧输出流
 */
public class SideOutput {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        DataStreamSource<String> source = env.socketTextStream("192.168.101.121", 7777);
        SingleOutputStreamOperator<WaterSensor> map = source.map(new WaterSensorMapFunction());
        OutputTag<WaterSensor> s1 = new OutputTag<>("s1", Types.POJO(WaterSensor.class));

        OutputTag<WaterSensor> s2 = new OutputTag<>("s2", Types.POJO(WaterSensor.class));

        //使用侧输出流
        SingleOutputStreamOperator<WaterSensor> process = map.process(new ProcessFunction<WaterSensor, WaterSensor>() {
            @Override
            public void processElement(WaterSensor sensor, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> collector) throws Exception {
                String sensorId = sensor.getId();
                if ("s1".equals(sensorId)) {
                    ctx.output(s1, sensor);
                } else if ("s2".equals(sensorId)) {
                    ctx.output(s2, sensor);
                } else {
                    collector.collect(sensor);
                }
            }
        });


        SideOutputDataStream<WaterSensor> side1 = process.getSideOutput(s1);
        side1.printToErr("s1");
        side1.print("s1");
        SideOutputDataStream<WaterSensor> side2 = process.getSideOutput(s2);
        side2.print("s2");
        process.print("主流");
        env.execute();

    }
}
